#!/bin/bash

# 询问用户输入DNS服务器地址
read -p "请输入主要的DNS服务器地址（如 8.8.8.8）： " PRIMARY_DNS
read -p "请输入备用的DNS服务器地址（如 8.8.4.4）： " SECONDARY_DNS
read -p "请输入备用的FallbackDNS地址（用空格分隔，例: 1.1.1.1 1.0.0.1）： " FALLBACK_DNS

# 备份现有的 resolved.conf 文件
echo "正在备份当前的 /etc/systemd/resolved.conf 到 /etc/systemd/resolved.conf.bak"
sudo cp /etc/systemd/resolved.conf /etc/systemd/resolved.conf.bak

# 修改 /etc/systemd/resolved.conf 文件
echo "正在将新的DNS设置写入 /etc/systemd/resolved.conf..."
sudo bash -c "cat > /etc/systemd/resolved.conf" <<EOL
[Resolve]
DNS=${PRIMARY_DNS} ${SECONDARY_DNS}
FallbackDNS=${FALLBACK_DNS}
EOL

# 将 /etc/resolv.conf 链接到 /run/systemd/resolve/resolv.conf
echo "正在将 /etc/resolv.conf 备份..."
sudo mv /etc/resolv.conf /etc/resolv.conf.bak

echo "正在将 /etc/resolv.conf 重新链接到 /run/systemd/resolve/resolv.conf..."
sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf

# 重启 systemd-resolved 服务
echo "正在重启 systemd-resolved 服务以应用新设置..."
sudo systemctl restart systemd-resolved

# 检查 DNS 配置状态
echo "当前的 DNS 配置状态："
resolvectl status

# 提示操作完成
echo "DNS 设置已成功更新，并确保 /etc/resolv.conf 链接到 /run/systemd/resolve/resolv.conf。"
